package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.BeanContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.ArticlesDto;
import com.itheima.dto.PageComDto;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Articles;
import com.itheima.pojo.User;
import com.itheima.service.ArticlesService;
import com.itheima.mapper.ArticlesMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
*
*/
@Service
public class ArticlesServiceImpl extends ServiceImpl<ArticlesMapper, Articles>
implements ArticlesService{
@Autowired ArticlesMapper articlesMapper;
@Autowired
    UserMapper userMapper;
    @Override
    public PageComDto search(Integer page, Integer pagesize, String keyword, Integer state) {
        IPage<Articles> p=new Page<>(page,pagesize);
        LambdaQueryWrapper<Articles> wrapper=new LambdaQueryWrapper<>();
        if(keyword!=null){
            wrapper.like(Articles::getTitle,keyword);
        }
        if(state!=null){
            wrapper.eq(Articles::getState,state);
        }
        IPage<Articles> articlesIPage = articlesMapper.selectPage(p, wrapper);
        List<Articles> records = articlesIPage.getRecords();
        String s = JSON.toJSONString(records);
        List<ArticlesDto> articlesDtos = JSON.parseArray(s, ArticlesDto.class);
        for (ArticlesDto articlesDto : articlesDtos) {
            Integer id = articlesDto.getCreatorID();
            User user1 = userMapper.selectById(id);
            articlesDto.setUsername(user1.getUsername());
        }
        PageComDto comDto=new PageComDto();
        comDto.setPageSize((int) articlesIPage.getSize());
        comDto.setItems(articlesDtos);
        comDto.setPage((int) articlesIPage.getCurrent());
        comDto.setCounts((int) articlesIPage.getTotal());
        comDto.setPages((int) articlesIPage.getPages());
        return comDto;
    }
}
